package com.financing.platform.service.impl;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.financing.platform.dto.UserInfoDTO;
import com.financing.platform.util.StringUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import com.financing.platform.dao.IFaNoticeDao;
import com.financing.platform.dao.IJpushMessageDao;
import com.financing.platform.dao.impl.JpushMessageDaoImpl;
import com.financing.platform.dto.FaNoticeDTO;
import com.financing.platform.dto.MessageJpushDTO;
import com.financing.platform.dto.MessageJpushUserPhoneAliasDTO;
import com.financing.platform.service.IFaNoticeService;
import com.financing.platform.vo.FaNoticeVO;

import cn.jpush.api.utils.Base64;

@Repository("faNoticeServiceImpl")
public class FaNoticeServiceImpl extends BaseServiceImpl implements IFaNoticeService {
	
	@Autowired
	private IFaNoticeDao faNoticeDao;
	
	@Autowired
	private IJpushMessageDao jpushMessageDaoImpl;
	
	@Value("#{settings['jiGuangPushRedrictOrderNotice']}")
	private String jpushRedrict;

	// 报单消息通知地址
	@Value("#{settings['jiGuangPushRedrictPhoNotice']}")
	private String jiGuangPushRedrictPhoNotice;


	private Map<String, FaNoticeDTO> noticeMap = null;
	{
		if(noticeMap == null){
			String telephone = "400-855-8085";
			String source = "SFA超级理财师";
			
			noticeMap = new HashMap<String, FaNoticeDTO>();
			
			FaNoticeDTO f01 = new FaNoticeDTO();
			f01.setTitle("您的产品预约成功！");
			f01.setSource("【"+source+"】");
			f01.setContent("您在超级理财师（www.superfa.cn）为【--clientName--】预约的【--productName--】已经成功！订单号为【--orderCode--】，预约时间【--createDate--】，金额【--orderAmount--】万元。如有疑问请电询" + telephone + "." 
					+ f01.getSource());
			noticeMap.put("01", f01);
			
			FaNoticeDTO f02 = new FaNoticeDTO();
			f02.setTitle("产品合同已寄出，请注意查收！");//您的【--productName--】
			f02.setSource("【"+source+"】");
			f02.setContent("您在超级理财师（www.superfa.cn）为【--clientName--】预约的【--productName--】合同已经寄出，敬请查收！订单号为【--orderCode--】，预约时间【--createDate--】，金额【--orderAmount--】万元！如有疑问请电询" 
					+ telephone + "." + f02.getSource());
			noticeMap.put("02", f02);
			
			FaNoticeDTO f03 = new FaNoticeDTO();
			f03.setTitle("对不起，您的产品预约失败！");
			f03.setSource("【"+source+"】");
			// f03.setContent("【--reason--】，您的客户【--clientName--】，订单号为【--orderCode--】，预约时间【--createDate--】，如有疑问请电询" + telephone + "." + f03.getSource());
			f03.setContent("您为客户【--clientName--】预约【--productName--】的订单，预约失败，订单号为【--orderCode--】，预约时间【--createDate--】，如有疑问请电询" + telephone + "." + f03.getSource());
			noticeMap.put("03", f03);
			
			FaNoticeDTO f04 = new FaNoticeDTO();
			f04.setTitle("对不起，您的产品订单失败！");
			f04.setSource("【"+source+"】");
			f04.setContent("【--reason--】您的客户【--clientName--】，订单号为【--orderCode--】，预约时间【--createDate--】，如有疑问请电询" + telephone + "." + f04.getSource());
			noticeMap.put("04", f04);
			
			FaNoticeDTO f05 = new FaNoticeDTO();
			f05.setTitle("已确认到款！");
			f05.setSource("【"+source+"】");
			f05.setContent("尊敬的客户你好，您为客户【--clientName--】预约的【--productName--】产品订单我们已确认到款！订单号为【--orderCode--】，预约时间【--createDate--】，如有疑问请电询" + telephone + "." + f05.getSource());
			noticeMap.put("05", f05);
			
			FaNoticeDTO f06 = new FaNoticeDTO();
			f06.setTitle("您的产品已结佣，请及时确认佣金到账！");
			f06.setSource("【"+source+"】");
			f06.setContent("尊敬的客户你好！您为客户【--clientName--】预约的【--productName--】产品订单已结佣！订单号为【--orderCode--】，预约时间【--createDate--】，如有疑问请电询" + telephone + "." + f06.getSource());
			noticeMap.put("06", f06);
			
			FaNoticeDTO f07 = new FaNoticeDTO();
			f07.setTitle("您的产品已结佣，请及时确认佣金到账！");
			f07.setSource("【"+source+"】");
			f07.setContent("你好，您为客户【--clientName--】预约的【--productName--】产品订单已后端结佣！订单号为【--orderCode--】，预约时间【--createDate--】，如有疑问请电询" + telephone + "." + f07.getSource());
			noticeMap.put("07", f07);
			
			FaNoticeDTO f08 = new FaNoticeDTO();
			f08.setTitle("交易结束！");
			f08.setSource("【"+source+"】");
			f08.setContent("你好，很高兴与您与您的客户【--clientName--】在【--productName--】产品的选择与我们合作，超级理财师期待以后能为您提供更多服务！再次感谢！订单号为【--orderCode--】，预约时间【--createDate--】，如有疑问请电询" + telephone + "." + f08.getSource());
			noticeMap.put("08", f08);

			FaNoticeDTO f09 = new FaNoticeDTO();
			f09.setTitle("您报单审核失败，请重新提交！");
			f09.setSource("【"+source+"】");
			f09.setContent("您好，您提交的【--clientName--】购买的【--productName--】报单资料审核失败，请重新提交或联系您的投资顾问" + telephone + "." + f08.getSource());
			noticeMap.put("10", f09);
		}
	}
	
	@Override
	public FaNoticeVO queryOrderDetailByOrderId(String id) throws Exception{
		return faNoticeDao.queryOrderDetailByOrderId(id);
	}
	
	@Override
	public int addFaOrderNotice(FaNoticeDTO notice) throws Exception {
		if (notice.getType() != null) {
			if(!notice.getType().equals("09")){// 09 有单通知
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				FaNoticeDTO tmpNotice = noticeMap.get(notice.getType());
				notice.setTitle(tmpNotice.getTitle());
				notice.setContent(tmpNotice.getContent());
				notice.setSource(tmpNotice.getSource());
	
				// 获取订单、产品信息
				FaNoticeVO orderDetail = faNoticeDao.queryOrderDetailByOrderId(notice.getOrderId());
				//获取订单管理者信息
				UserInfoDTO userInfoDTO =  faNoticeDao.queryUserInfoByOrderId(notice.getOrderId());
				if(userInfoDTO != null  && StringUtils.isNotBlank(userInfoDTO.getUserNickname())){
					String userInfo = "【"+userInfoDTO.getUsername()+"："+userInfoDTO.getTelePhone()+"】";
					notice.setContent(notice.getContent().replace("400-855-8085",userInfo));
				}
				notice.setTitle(notice.getTitle().replace("--productName--", orderDetail.getProductName()));
				
				notice.setContent(notice.getContent()
						.replace("--productName--", orderDetail.getProductName())
						.replace("--orderAmount--", orderDetail.getOrderAmount().divide(new BigDecimal("10000"),2,BigDecimal.ROUND_HALF_UP).toString())
						.replace("--reason--", orderDetail.getReason())
						.replace("--clientName--", orderDetail.getClientName())
						.replace("--createDate--", sdf.format(orderDetail.getCreateDate()))
						.replace("--orderCode--", orderDetail.getOrderCode())
				);
	
				notice.setProductCode(orderDetail.getProductCode());
				notice.setProductId(orderDetail.getProductId());
				notice.setOrderId(orderDetail.getOrderId());
				notice.setFaId(orderDetail.getFaId());
				notice.setStatus("01");
			}
			// 极光推送消息
			
			// 根据用户查询出绑定的设备标示
			List<MessageJpushUserPhoneAliasDTO> phoneAlias = jpushMessageDaoImpl.queryJpushUserPhonealias(notice.getFaId());
			if(null != phoneAlias && phoneAlias.size() >= 1){
				MessageJpushDTO messageJpushDTO = new MessageJpushDTO();
				if(StringUtils.isNotBlank(notice.getJpushSource()) && StringUtils.equals(notice.getJpushSource(), "shop")){
					messageJpushDTO.setFpJpushMsgRec(phoneAlias.get(0).getFpJpushAliasShop());
				}else{
					messageJpushDTO.setFpJpushMsgRec(phoneAlias.get(0).getFpJpushAlias());
				}
				messageJpushDTO.setFpJpushTitle(notice.getTitle());
				messageJpushDTO.setFpJpushContent(notice.getContent());
				
//				messageJpushDTO.setFpJpushRedrict("/#/product/xtzgdetail/" + notice.getProductCode());
				messageJpushDTO.setFpJpushRedrict(new String(Base64.encode(URLEncoder.encode(jpushRedrict).getBytes())));
				
				messageJpushDTO.setFpJpushMsgType("01");// 消息类型 01:系统消息 02:运营推送
				messageJpushDTO.setFpJpushSendType("01");// 推送消息类型  01:实时推送  02:定时推送
				messageJpushDTO.setCreateBy(notice.getFaId() + "");
				messageJpushDTO.setCreateDate(new Date());
				messageJpushDTO.setUpdateBy(notice.getFaId() + "");
				messageJpushDTO.setUpdateDate(new Date());
				jpushMessageDaoImpl.addJpushMessage(messageJpushDTO);
			}
			return faNoticeDao.addFaOrderNotice(notice);
		}
		return 0;
	}

	@Override
	public int addFaPhoNotice(FaNoticeDTO notice) throws Exception {
			//报单通知
			notice.setType("10");
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			FaNoticeDTO tmpNotice = noticeMap.get(notice.getType());
			notice.setTitle(tmpNotice.getTitle());
			notice.setContent(tmpNotice.getContent());
			notice.setSource(tmpNotice.getSource());

			// 获取订单、产品信息
			FaNoticeVO orderDetail = faNoticeDao.queryOrderDetailByOrderId(notice.getOrderId());

			//获取订单管理者信息
			UserInfoDTO userInfoDTO =  faNoticeDao.queryUserInfoByOrderId(notice.getOrderId());
			if(userInfoDTO != null){
				String userInfo = "【"+userInfoDTO.getUsername()+"："+userInfoDTO.getTelePhone()+"】";
				notice.setContent(notice.getContent().replace("400-855-8085",userInfo));
			}

			notice.setTitle(notice.getTitle().replace("--productName--", orderDetail.getProductName()));

			notice.setContent(notice.getContent()
					.replace("--productName--", orderDetail.getProductName())
					.replace("--orderAmount--", orderDetail.getOrderAmount().divide(new BigDecimal("10000"),2,BigDecimal.ROUND_HALF_UP).toString())
					.replace("--reason--", orderDetail.getReason())
					.replace("--clientName--", orderDetail.getClientName())
					.replace("--createDate--", sdf.format(orderDetail.getCreateDate()))
					.replace("--orderCode--", orderDetail.getOrderCode())
			);

			notice.setProductCode(orderDetail.getProductCode());
			notice.setProductId(orderDetail.getProductId());
			notice.setOrderId(orderDetail.getOrderId());
			notice.setFaId(orderDetail.getFaId());
			notice.setStatus("01");

			// 极光推送消息

			// 根据用户查询出绑定的设备标示
			List<MessageJpushUserPhoneAliasDTO> phoneAlias = jpushMessageDaoImpl.queryJpushUserPhonealias(notice.getFaId());
			if(null != phoneAlias && phoneAlias.size() >= 1){
				MessageJpushDTO messageJpushDTO = new MessageJpushDTO();

				messageJpushDTO.setFpJpushMsgRec(phoneAlias.get(0).getFpJpushAlias());
				messageJpushDTO.setFpJpushTitle(notice.getTitle());
				messageJpushDTO.setFpJpushContent(notice.getContent());
				messageJpushDTO.setFpJpushRedrict(new String(Base64.encode(URLEncoder.encode(jiGuangPushRedrictPhoNotice).getBytes())));

				messageJpushDTO.setFpJpushMsgType("01");// 消息类型 01:系统消息 02:运营推送
				messageJpushDTO.setFpJpushSendType("01");// 推送消息类型  01:实时推送  02:定时推送
				messageJpushDTO.setCreateBy(notice.getFaId() + "");
				messageJpushDTO.setCreateDate(new Date());
				messageJpushDTO.setUpdateBy(notice.getFaId() + "");
				messageJpushDTO.setUpdateDate(new Date());
				jpushMessageDaoImpl.addJpushMessage(messageJpushDTO);
			}
			return faNoticeDao.addFaOrderNotice(notice);

	}

	public static void main(String[] args) {
		String tmp = "aaa--clientName--bbb";
		System.out.println(tmp.replace("--clientName--", null));
	}

	@Override
	public int addFaNotice(FaNoticeDTO notice) throws Exception {
		 faNoticeDao.addFaOrderNotice(notice);
		 return 0;
	}
}
